package com.alibaba.serverless;

import com.alibaba.serverless.common.ApiGwRequest;
import com.alibaba.serverless.common.ApiGwResponse;
import com.aliyun.fc.runtime.Context;
import com.aliyun.fc.runtime.FunctionComputeLogger;
import com.aliyun.fc.runtime.FunctionInitializer;
import com.aliyun.fc.runtime.PojoRequestHandler;

import java.util.UUID;

public class WebHandler implements FunctionInitializer, PojoRequestHandler<ApiGwRequest, ApiGwResponse> {

	/*
	 * 云函数初始化
	 * 
	 * @see com.aliyun.fc.runtime.FunctionInitializer#initialize(com.aliyun.fc.
	 * runtime.Context)
	 */
	@Override
	public void initialize(Context context) {
		FunctionComputeLogger logger = context.getLogger();
		logger.debug(String.format("RequestID is %s %n", context.getRequestId()));
	}

	/*
	 * Web云函数处理入口
	 * 
	 * @see com.aliyun.fc.runtime.PojoRequestHandler#handleRequest(java.lang.Object,
	 * com.aliyun.fc.runtime.Context)
	 */
	@Override
	public ApiGwResponse handleRequest(ApiGwRequest request, Context context) {
		FunctionComputeLogger logger = context.getLogger();
		String newUUID = UUID.randomUUID().toString();

		String bodyContext = "<html>" + "<h1>您好！ 生成了一个UUID:" + newUUID + "</h1><br>"
				+ "</html>";

		ApiGwResponse response = new ApiGwResponse();
		response.getHeaders().put("responseHeader", "testValue");
		response.getHeaders().put("Content-type", "text/html; charset=utf-8");
		// boolean isBase = request.getIsBase64Encoded();
		boolean isBase = false;
		// 响应内容是JSON，不用编码, 建议和 request内部编码保持一致

		logger.info("Response返回:" + bodyContext);

		response.setBody(bodyContext);
		response.setBase64Encoded(false);
		response.setStatusCode(200);

		return response;

	}
	
}
